package com.vedana.bankmobile.json;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;
import com.vedana.bankmobile.services.BankMobileServiceImpl;
import com.vedana.bankmobile.services.BankMobileService;
import com.vedana.bankmobile.shared.Operation;

/**
 * BankMobile service : JSON RPC adapter
 * 
 * @author Didier MOISE
 */
public class BankMobileJsonServlet extends HttpServlet {

	private static final long serialVersionUID = -8934559464736680431L;

	private BankMobileService service = new BankMobileServiceImpl();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		boolean scriptTag = false;
		String cb = req.getParameter("callback");
		if (cb != null) {
		    scriptTag = true;
		    resp.setContentType("text/javascript");
		} else {
		    resp.setContentType("application/x-json");
		}
		PrintWriter out = resp.getWriter();
		
		// Call service
		List<Operation> operations = getAllOperations(123456789);
		
		// Convert to JSON
		if (scriptTag) {
		    out.write(cb + "(");
		}
		try {
			JSONArray array = operationsToJson(operations); 
			out.write(array.toString());
		} catch (JSONException e) {
			out.write("");
		}
		if (scriptTag) {
		    out.write(");");
		}
	}
	
	private List<Operation> getAllOperations(long accountId) {
		return service.getAllOperations(accountId);
	}

	private JSONArray operationsToJson(List<Operation> operations) throws JSONException {
		DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
		JSONArray array = new JSONArray();
		
		for (Operation operation : operations) {
			JSONObject obj = new JSONObject();
			
			obj.put("date", df.format(operation.getDate()));
			obj.put("label", operation.getLabel());
			obj.put("value", operation.getValue());
			
			array.put(obj);
		}
		return array;
	}
}
